package org.batyrov.equery.action.admin;

import org.batyrov.equery.action.BaseAction;
import org.batyrov.equery.action.Const;
import org.batyrov.equery.bean.User;
import org.batyrov.equery.dao.Dao;

/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 25.07.2009
 * Time: 0:01:16
 * To change this template use File | Settings | File Templates.
 */
public class SaveUser extends BaseAction {
    private long id = -1;
    private String username;
    private String password;
    private String cpassword;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getCpassword() {
        return cpassword;
    }

    public void setCpassword(String cpassword) {
        this.cpassword = cpassword;
    }

    @Override
    public String execute() throws Exception {
        super.execute();
        if (password == null) {
            addActionError(getText("you_must_enter_password"));
            return Const.ERROR;
        }
        if (!password.equals(cpassword)) {
            addActionError(getText("password_not_equals"));
            return Const.ERROR;
        }
        if (id == -1) {
            User user = new User();
            user.setPassword(password);
            user.setUsername(username);
            if (dao.persist(user)) {
                return Const.SUCCESS;
            }
        } else {
            User user = em.find(User.class, id);
            if (user == null) {
                addActionError(getText("user_not_found"));
                return Const.ERROR;
            }
            em.getTransaction().begin();
            try {
                user.setUsername(username);
                if (!password.trim().equals("")){
                    user.setPassword(password);
                }
                em.getTransaction().commit();
                return Const.SUCCESS;
            } catch (Exception e) {
                e.printStackTrace();
                em.getTransaction().rollback();
                return Const.ERROR;
            }
        }
        return Const.SUCCESS;
    }
}
